package com.cap.bts.crmdp.httpconnection;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cap.bts.commonfunc.common.util.DateUtil;
import com.cap.bts.crmdp.dealer.masterinfo.constants.MasterInfoConstants;
import com.cap.bts.crmdp.dealer.masterinfo.utils.MasterInfoUtils;

public class HttpConnectionUtils {

    private static final Logger LOGGER = Logger.getLogger(HttpConnectionUtils.class);

    public HttpConnectionUtils() {
    }

    public static String openHttpsConnection(final String urlPath, String charset,
                                             int connectTimeout, int readTimeout,
                                             Map<String, String> headerMap) throws IOException {
        HttpURLConnection conn = null;
        URL url = null;
        InputStreamReader inReader = null;
        BufferedReader reader = null;
        try {
            url = new URL(urlPath);
            conn = (HttpURLConnection) url.openConnection();
            if (headerMap != null) {
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            conn.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; "
                        + "SailBrowser; Maxthon; Alexa Toolbar; .NET CLR 2.0.50727)");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);
            conn.connect();
            inReader = new InputStreamReader(conn.getInputStream(), Charset.forName(charset));
            reader = new BufferedReader(inReader);
            String str = null;
            StringBuffer returnStr = new StringBuffer(200);
            while ((str = reader.readLine()) != null) {
                returnStr.append(str);
            }
            String result = returnStr.toString();
            return result;
        } catch (IOException e) {
            LOGGER.error(e);
            throw e;
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (inReader != null) {
                inReader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
            conn = null;
            url = null;
        }
    }

    /** 
     * 下载远程文件并保存到本地  
     * @param remoteFilePath 远程文件路径  
     * @param localFilePath 本地文件存放路径 
     * @param fileName 本地文件名称
     * @throws IOException 
     * @throws Exception 
     */
    public static File downloadFile(String remoteFilePath, String localFilePath, String fileName)
                                                                                                 throws IOException {

        URL urlfile = null;
        HttpURLConnection httpUrl = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        FileOutputStream fout = null;
        File f = new File(localFilePath);
        if (!f.exists() && !f.isDirectory()) {
            f.mkdirs();
        }

        File csvFile = null;
        try {
            csvFile = new File(localFilePath + fileName + ".csv");
            urlfile = new URL(remoteFilePath);
            httpUrl = (HttpURLConnection) urlfile.openConnection();
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());
            fout = new FileOutputStream(csvFile);
            bos = new BufferedOutputStream(fout);
            int len = 2048;
            byte[] b = new byte[len];
            while ((len = bis.read(b)) != -1) {
                //解决内容乱码问题
                //bos.write(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF })
                bos.write(b, 0, len);
            }
            bos.flush();
            bis.close();
            httpUrl.disconnect();
            return csvFile;
        } catch (IOException e) {
            LOGGER.error("", e);
        } finally {
            if (bos != null) {
                bos.close();
            }
            if (fout != null) {
                fout.close();
            }
            if (bis != null) {
                bis.close();
            }
            if (httpUrl != null) {
                httpUrl.disconnect();
            }
        }
        return csvFile;
    }

    @SuppressWarnings("rawtypes")
    public static void main(String[] args) {
        String urlPath = MasterInfoConstants.QUERY_URL_PATH;
        String charset = "UTF-8";
        int connectTimeout = 6000;
        int readTimeout = 6000;
        //String fileType = MasterInfoConstants.FILE_TYPE_TYREPRODUCTFILE
        String fileType = MasterInfoConstants.FILE_TYPE_OTHERPRODUCTFILE;
        //String fileType = MasterInfoConstants.FILE_TYPE_SERVICEFILE

        urlPath += "fileType=" + fileType;
        try {
            String result = HttpConnectionUtils.openHttpsConnection(urlPath, charset,
                connectTimeout, readTimeout, null);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String dataString = jsonObject.getString("data");

            //System.out.println("dataString:" + dataString)

            JSONArray jsonArray = JSONArray.parseArray(dataString);

            String fileName = null;
            String fileUrl = null;
            String currentDte = DateUtil.getDateText(new Date());
            //本地存储目录
            String localFilePath = MasterInfoConstants.getLOCALHOSTPATH_STRING() + fileType + "/"
                                   + currentDte + "/";
            Map<String, Object> dataMap = new HashMap<String, Object>();
            int num = 0;
            for (Iterator iterator = jsonArray.iterator(); iterator.hasNext();) {
                JSONObject object = (JSONObject) iterator.next();
                fileName = object.getString("fileName");//获取文件下载的名称
                fileUrl = object.getString("fileUrl");//获取文件下载的地址

                fileName = fileName.substring(0, fileName.indexOf(".csv"));
                //组成访问的url
                urlPath = MasterInfoConstants.DOWNLOAD_URL_PATH_STRING + fileUrl;

                File csvFile = downloadFile(urlPath, localFilePath, fileName);

                System.out.println(csvFile.getPath());
                List<String> list = MasterInfoUtils.analyzeCsv(csvFile);
                List<Map<String, Object>> dataList = MasterInfoUtils.combinationList(list);

                dataMap.put("dataList" + num, dataList);
                num++;
            }

            //file.delete()

        } catch (Exception e) {
            LOGGER.error("提取信息失败", e);

        }
    }
}
